package com.foodorder.controller;

import com.foodorder.entity.Order;
import com.foodorder.entity.OrderItem;
import com.foodorder.service.OrderService;
import com.foodorder.utils.ResponseResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@Slf4j
@RestController
@RequestMapping("/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody Order order) {
        try {
            log.info("收到创建订单请求: {}", order);
            Order createdOrder = orderService.createOrder(order);
            return ResponseEntity.ok(ResponseResult.success(createdOrder));
        } catch (Exception e) {
            log.error("创建订单失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "创建订单失败: " + e.getMessage()));
        }
    }

    /**
     * 查询订单详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getOrderById(@PathVariable Long id) {
        try {
            Order order = orderService.findById(id);
            if (order == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(ResponseResult.success(order));
        } catch (Exception e) {
            log.error("查询订单失败, id={}: {}", id, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "查询订单失败: " + e.getMessage()));
        }
    }

    /**
     * 根据订单号查询订单
     */
    @GetMapping("/by-order-no/{orderNo}")
    public ResponseEntity<?> getOrderByOrderNo(@PathVariable String orderNo) {
        try {
            Order order = orderService.findByOrderNo(orderNo);
            if (order == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(ResponseResult.success(order));
        } catch (Exception e) {
            log.error("查询订单失败, orderNo={}: {}", orderNo, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "查询订单失败: " + e.getMessage()));
        }
    }

    /**
     * 查询用户的订单列表
     */
    @GetMapping("/user/{userId}")
    @PreAuthorize("authentication.principal.id == #userId or hasRole('ADMIN')")
    public ResponseEntity<?> getUserOrders(
            @PathVariable Long userId,
            @RequestParam(required = false) Order.OrderStatus status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            Page<Order> orders;
            
            if (status != null) {
                // 按状态查询
                orders = orderService.findByUserIdAndStatus(userId, status, pageRequest);
            } else {
                // 查询所有状态
                orders = orderService.findByUserId(userId, pageRequest);
            }
            
            return ResponseEntity.ok(ResponseResult.success(orders));
        } catch (Exception e) {
            log.error("查询用户订单失败, userId={}: {}", userId, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "查询用户订单失败: " + e.getMessage()));
        }
    }

    /**
     * 查询店铺的订单列表
     */
    @GetMapping("/store/{storeId}")
    @PreAuthorize("hasAnyRole('MERCHANT', 'ADMIN')")
    public ResponseEntity<?> getStoreOrders(
            @PathVariable Long storeId,
            @RequestParam(required = false) Order.OrderStatus status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            Page<Order> orders;
            
            if (status != null) {
                // 按状态查询
                orders = orderService.findByStoreIdAndStatus(storeId, status, pageRequest);
            } else {
                // 查询所有状态
                orders = orderService.findByStoreId(storeId, pageRequest);
            }
            
            return ResponseEntity.ok(ResponseResult.success(orders));
        } catch (Exception e) {
            log.error("查询店铺订单失败, storeId={}: {}", storeId, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "查询店铺订单失败: " + e.getMessage()));
        }
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAnyRole('MERCHANT', 'ADMIN')")
    public ResponseEntity<?> updateOrderStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> statusMap) {
        try {
            String statusStr = statusMap.get("status");
            if (statusStr == null) {
                return ResponseEntity.badRequest()
                        .body(ResponseResult.error(400, "缺少状态参数"));
            }
            
            Order.OrderStatus status = Order.OrderStatus.valueOf(statusStr);
            orderService.updateOrderStatus(id, status);
            
            return ResponseEntity.ok(ResponseResult.success("订单状态更新成功"));
        } catch (IllegalArgumentException e) {
            log.error("无效的订单状态: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "无效的订单状态"));
        } catch (Exception e) {
            log.error("更新订单状态失败, id={}: {}", id, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "更新订单状态失败: " + e.getMessage()));
        }
    }

    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public ResponseEntity<?> cancelOrder(
            @PathVariable Long id,
            @RequestBody Map<String, String> cancelInfo) {
        try {
            String reason = cancelInfo.get("reason");
            orderService.cancelOrder(id, reason);
            
            return ResponseEntity.ok(ResponseResult.success("订单取消成功"));
        } catch (Exception e) {
            log.error("取消订单失败, id={}: {}", id, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "取消订单失败: " + e.getMessage()));
        }
    }

    /**
     * 确认支付
     */
    @PostMapping("/{id}/payment")
    public ResponseEntity<?> confirmPayment(
            @PathVariable Long id,
            @RequestBody Map<String, String> paymentInfo) {
        try {
            String paymentMethod = paymentInfo.get("paymentMethod");
            String transactionId = paymentInfo.get("transactionId");
            
            if (paymentMethod == null || transactionId == null) {
                return ResponseEntity.badRequest()
                        .body(ResponseResult.error(400, "支付信息不完整"));
            }
            
            orderService.confirmPayment(id, paymentMethod, transactionId);
            
            return ResponseEntity.ok(ResponseResult.success("支付确认成功"));
        } catch (Exception e) {
            log.error("支付确认失败, id={}: {}", id, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "支付确认失败: " + e.getMessage()));
        }
    }

    /**
     * 订单统计数据
     */
    @GetMapping("/stats/user/{userId}")
    @PreAuthorize("authentication.principal.id == #userId or hasRole('ADMIN')")
    public ResponseEntity<?> getUserOrderStats(@PathVariable Long userId) {
        try {
            Map<String, Object> stats = orderService.getUserOrderStats(userId);
            return ResponseEntity.ok(ResponseResult.success(stats));
        } catch (Exception e) {
            log.error("获取用户订单统计失败, userId={}: {}", userId, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "获取订单统计失败: " + e.getMessage()));
        }
    }

    /**
     * 店铺订单统计
     */
    @GetMapping("/stats/store/{storeId}")
    @PreAuthorize("hasAnyRole('MERCHANT', 'ADMIN')")
    public ResponseEntity<?> getStoreOrderStats(@PathVariable Long storeId) {
        try {
            Map<String, Object> stats = orderService.getStoreOrderStats(storeId);
            return ResponseEntity.ok(ResponseResult.success(stats));
        } catch (Exception e) {
            log.error("获取店铺订单统计失败, storeId={}: {}", storeId, e.getMessage(), e);
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(400, "获取订单统计失败: " + e.getMessage()));
        }
    }
} 